package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.UserHolder;
import com.tanhua.api.db.UserApi;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.FriendApi;
import com.tanhua.api.mongo.RecommendUserApi;
import com.tanhua.api.mongo.UserLikeApi;
import com.tanhua.api.mongo.VisitorsApi;
import com.tanhua.db.User;
import com.tanhua.db.UserInfo;
import com.tanhua.mongo.Friend;
import com.tanhua.mongo.UserLike;
import com.tanhua.mongo.Visitors;
import com.tanhua.template.AipFaceTemplate;
import com.tanhua.template.HuanXinTemplate;
import com.tanhua.template.OssTemplate;
import com.tanhua.template.SmsTemplate;
import com.tanhua.utils.JwtUtil;
import com.tanhua.vo.CountsVo;
import com.tanhua.vo.PageBeanVo;
import com.tanhua.vo.UserInfoVo;
import com.tanhua.vo.UserLikeListVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Reference
    private UserApi userApi;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Reference
    private FriendApi friendApi;
    @Reference
    private UserLikeApi userLikeApi;
    @Reference
    private VisitorsApi visitorsApi;
    @Reference
    private RecommendUserApi recommendUserApi;



    public ResponseEntity saveUser(@RequestBody User user){
        Long id = userApi.saveUser(user);
        return ResponseEntity.ok(id);
    }


    public ResponseEntity findByPhone(String  phone){
        User user = userApi.findByPhone(phone);
        return ResponseEntity.ok(user);
    }


    public ResponseEntity login(String phone){

        // 2 获取随机6位数
        String code = "123456";
        // 3 调用阿里云工具类抽成的启动器模板
        //smsTemplate.sendSms(phone,code);
        System.out.println("发送的验证码是："+code);
        //4  放入redis中（设置过期时间）
        stringRedisTemplate.opsForValue().set("SMS_CODE_"+phone,code,10, TimeUnit.MINUTES);
        //扩展取：String value=stringRedisTemplate.opsForValue().get("key");
        //5 返回值
        return ResponseEntity.ok(null);

    }

    public ResponseEntity loginVerification(String phone, String yzm) {
        //1 获取redis中的验证码
        String redis_yzm = stringRedisTemplate.opsForValue().get("SMS_CODE_" + phone);
        //2 对比和页面用户写入的验证码
        if(!StrUtil.equals(yzm,redis_yzm)){
            //3 不一致--直接给错误信息
            return ResponseEntity.status(500).body("验证码错误");
        }
        //优化验证码：用完即删
        stringRedisTemplate.delete("SMS_CODE_" + phone);
        //4 一致--带着手机号去查询
        User user = userApi.findByPhone(phone);


        //6 查到了（老用户） return false
        Boolean flag=false;

        //5 没查到（新用户）--注册 return true
        if(user==null){
            user=new User();
            user.setPhone(phone);
            Long id = userApi.saveUser(user);//注册探花
            huanXinTemplate.register(id);     //注册成环信用户
            user.setId(id);
            flag=true;
        }

        //将当前用户加密成一串字符串token
        String token = JwtUtil.createToken(user.getPhone(), "tanhua");
        //当前用户对象转成json
        String user_json =JSON.toJSONString(user);
        //将token放入redis中
        stringRedisTemplate.opsForValue().set("TOKEN_"+token,user_json,1,TimeUnit.DAYS);
        //返回json
        Map json_map=new HashMap<String,Object>();
        json_map.put("token",token); //待会来优化
        json_map.put("isNew",flag);
        return ResponseEntity.ok(json_map);
    }

    public ResponseEntity loginReginfo(UserInfo userInfo, String token) {
        // 1 先根据token获取redis的当前登录用户
        User user=findByToken(token);
        // 2 将登录用户的id赋值给userInfo的id (让主键一一对应)
        System.out.println(user.getId());
        userInfo.setId(user.getId());
        // 3 调用服务方法做保存
        userInfoApi.saveUserInfo(userInfo);
        return ResponseEntity.ok(null);

    }

    //从redis中根据token获取当前登录用户信息（user）
    public User findByToken(String token) {
        String user_json = stringRedisTemplate.opsForValue().get("TOKEN_" + token);
        User user = JSON.parseObject(user_json, User.class);
        return user;
    }

    public ResponseEntity head(MultipartFile headPhoto, String token) throws IOException {

        // 人脸识别
        boolean flag = aipFaceTemplate.detect(headPhoto.getBytes());
        if(flag==false){
            //识别失败
            return ResponseEntity.status(500).body("人脸识别失败~");
        }
        // 传递图片到oss
        String url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        // 根据token获取用户id
        User user = findByToken(token);
        //根据id修改userInfo的图片oss地址
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setAvatar(url); //图片在oss的地址
        userInfo.setCoverPic(url); //封面

        //修改userInfo
        userInfoApi.updateUserInfo(userInfo);
        return ResponseEntity.ok(null);


    }

    //根据id做查询
    public ResponseEntity findUserInfoVo(Long id) {
        UserInfo userInfo=userInfoApi.findById(id);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        return ResponseEntity.ok(userInfoVo);
    }

    public ResponseEntity updateData(UserInfo userInfo,String token) {
        // 获取登录用户的id
        User user = findByToken(token);
        // 设置给userInfo的id
        userInfo.setId(user.getId());
        //带着userInfo去做修改
        userInfoApi.updateUserInfo(userInfo);
        return ResponseEntity.ok(null);
    }
    public ResponseEntity counts() {

        // 1 获取互相喜欢的总数
        Integer eachLoveCount=friendApi.findCount(UserHolder.getUser().getId());
        // 2 获取喜欢的总数
        Integer loveCount=userLikeApi.findLoveCount(UserHolder.getUser().getId());
        // 3 获取粉丝的总数
        Integer fanCount=userLikeApi.findFanCount(UserHolder.getUser().getId());
        //组装
        CountsVo vo = new CountsVo(eachLoveCount,loveCount,fanCount);
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findMyCountList(Integer type, Integer page, Integer pagesize) {

        PageBeanVo pageBean=null;
        List<UserLikeListVo> voList=new ArrayList<>();
        // 1 判断
        switch (type){
            case 1:{
                // 互相喜欢的列表
                pageBean=friendApi.findFriends(page,pagesize,UserHolder.getUser().getId());
                //获取userinfo的详情
                List<Friend> items = (List<Friend>) pageBean.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (Friend item : items) {
                        UserInfo userInfo = userInfoApi.findById(item.getFriendId());
                        UserLikeListVo vo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo,vo);
                        voList.add(vo);
                    }
                }
                break;
            }
            case 2:{
                // 喜欢的列表
                pageBean= userLikeApi.findLoveList(page,pagesize,UserHolder.getUser().getId());
                //获取userinfo的详情
                List<UserLike> items = (List<UserLike>) pageBean.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (UserLike item : items) {
                        UserInfo userInfo = userInfoApi.findById(item.getLikeUserId());
                        UserLikeListVo vo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo,vo);
                        voList.add(vo);
                    }
                }
                break;
            }
            case 3:{
                // 粉丝的列表
                pageBean= userLikeApi.findFanList(page,pagesize,UserHolder.getUser().getId());
                //获取userinfo的详情
                List<UserLike> items = (List<UserLike>) pageBean.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (UserLike item : items) {
                        UserInfo userInfo = userInfoApi.findById(item.getUserId());
                        UserLikeListVo vo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo,vo);
                        voList.add(vo);
                    }
                }
                break;
            }
            case 4:{
                // 访客的列表
                pageBean= visitorsApi.findHistoryList(page,pagesize,UserHolder.getUser().getId());
                //获取userinfo的详情
                List<Visitors> items = (List<Visitors>) pageBean.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (Visitors item : items) {
                        UserInfo userInfo = userInfoApi.findById(item.getVisitorUserId());
                        UserLikeListVo vo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo,vo);
                        //缘分值
                        Long score = recommendUserApi.findScore(item.getVisitorUserId(), UserHolder.getUser().getId());
                        vo.setMatchRate(score.intValue());
                        voList.add(vo);
                    }
                }
                break;
            }
        }


        pageBean.setItems(voList);

        return ResponseEntity.ok(pageBean);

    }

    public ResponseEntity fanstoFriend(Integer fanId) {

        // friend表中插入2条数据
        friendApi.addFriends(UserHolder.getUser().getId(),fanId);

        // userLike表中删除一条数据
        userLikeApi.removeFans(fanId,UserHolder.getUser().getId());

        return ResponseEntity.ok(null);
    }

    public ResponseEntity removeLove(Integer loveId) {

        // 1 判断用户点击的是哪个取消喜欢
        Boolean flag=friendApi.isFriend(UserHolder.getUser().getId(),loveId);
        if(flag){
            // 2 互相喜欢的---删除好友表的2条数据 userLike添加一个粉丝数据
            friendApi.removeFriend(UserHolder.getUser().getId(),loveId);
            userLikeApi.addFans(UserHolder.getUser().getId(),loveId);
        }else{
            // 3 喜欢--直接删除喜欢的这个人
            userLikeApi.removeFans(UserHolder.getUser().getId().intValue(),loveId.longValue());
        }

        return ResponseEntity.ok(null);

    }
}